<template>
  <div :class="classes">
    <div class="input-box">
      <input
        v-model="searchVal"
        type="text"
        :placeholder="placeholder"
        @keydown.enter="handleSearch"
      />
      <img
        v-show="searchVal && delAble"
        src="./images/del.png"
        class="del-icon"
        alt=""
        @click="delTitle"
      />
    </div>

    <button @click="handleSearch">{{ searchBtnTitle }}</button>
  </div>
</template>
<script name="ItSearch" setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  shape: {
    type: String,
    default: 'plain',
    validator: function (value) {
      return ['plain', 'round', 'circle'].indexOf(value) !== -1
    },
  },
  searchTitle: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '请输入关键词进行检索',
  },
  searchBtnTitle: {
    type: String,
    default: '搜索',
  },
  delAble: {
    //是否有清空按钮
    type: Boolean,
    default: false,
  },
})

const classes = computed(() => ({
  'it-search': true,
  'it-search--icon': true,
  [`it-search--${props.shape}`]: true,
}))

let searchVal = ref(props.searchTitle)

watch(
  () => props.searchTitle,
  (newVal) => {
    searchVal.value = newVal
  }
)

const emits = defineEmits(['onSearch'])
const handleSearch = () => {
  emits('onSearch', { value: searchVal.value })
}
const getValue = () => {
  return searchVal.value
}

defineExpose({ getValue })

const delTitle = () => {
  searchVal.value = ''
  handleSearch()
}
</script>

<style scoped>
.it-search {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 6px 0 12px;
}

.it-search--icon {
  padding-left: 40px;
}

.it-search--icon::before {
  content: '';
  position: absolute;
  left: 12px;
  top: 50%;
  width: 20px;
  height: 20px;
  transform: translateY(-50%);
  background-image: url('./images/search-icon.png');
  background-size: 20px 20px;
  background-position: center center;
  background-repeat: no-repeat;
}

.input-box {
  height: 100%;
  width: calc(100% - 100px);
  position: relative;
}

.it-search input {
  padding-right: 20px;
  width: 100%;
  height: 100%;
}

.it-search button {
  padding: 0 22px;
  height: 34px;
  background: #206ef2;
  border-radius: 6px 6px 6px 6px;
  opacity: 1;
  font-size: 16px;
  color: #ffffff;
  white-space: nowrap;
  margin: 5px 0;
}

.it-search--plain {
  background: #ffffff;
  border-radius: 6px;
}

.it-search--round {
  background: #ffffff;
  box-shadow: 0px 4px 6px 1px rgba(32, 110, 242, 0.1);
  border-radius: 23px;
}

.it-search.it-search--round button {
  border-radius: 17px;
}

.del-icon {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  transform: translateY(-50%);
  right: 5px;
  cursor: pointer;
}
.it-search:deep(input),
.it-search:deep(input::placeholder) {
  line-height: 1.8;
}
</style>
